package com.mvc.start.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Map;

/**
 * @author JayEinstein
 */
@Component
@Slf4j
public class AccessLogGatewayFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        URI uri = request.getURI();
        String host = uri.getHost();
        String path = uri.getPath();
        String query = uri.getQuery();

        log.info("filter log => {}, {}, {}", host, path, query);

        Map<String, Object> attributes = exchange.getAttributes();
        log.info("access: {}", attributes);

        Flux<DataBuffer> body = request.getBody();
        log.info("body: {}", body);

        return chain.filter(exchange);
    }

}
